package com.toommi.refuse.service.impl;

import com.toommi.refuse.common.enums.StatisticsTypeEnum;
import com.toommi.refuse.common.util.DateUtil;
import com.toommi.refuse.entity.RecycleStatistics;
import com.toommi.refuse.entity.RecycleStatisticsExample;
import com.toommi.refuse.entity.WechatUserHousehold;
import com.toommi.refuse.entity.WechatUserHouseholdExample;
import com.toommi.refuse.enums.RecycleRecordExceptionEnum;
import com.toommi.refuse.exception.RecycleRecordException;
import com.toommi.refuse.mapper.RecycleStatisticsMapper;
import com.toommi.refuse.mapper.WechatUserHouseholdMapper;
import com.toommi.refuse.model.BenefitModel;
import com.toommi.refuse.model.BenefitStatisticsModel;
import com.toommi.refuse.service.RecycleStatisticsService;
import lombok.AllArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;

import java.math.BigDecimal;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import static com.toommi.refuse.common.util.DateUtil.DATE_FORMATE_YM;
import static com.toommi.refuse.common.util.DateUtil.DATE_FORMAT_YMD;

/**
 * @author yangg
 * @since 2019-08-02 10:41
 */
@Service
@Slf4j
@AllArgsConstructor
public class RecycleStatisticsServiceImpl implements RecycleStatisticsService {

    private RecycleStatisticsMapper statisticsMapper;

    private WechatUserHouseholdMapper wechatUserHouseholdMapper;

    @Override
    public void addRecycleStatistics(long houseId, double weight, BigDecimal money, String refuseType) {

        //  直接在统计内记录每天的合计以及每月的合计
        insertStatisticsRecord(houseId, weight, money, refuseType, DATE_FORMAT_YMD, StatisticsTypeEnum.DAY);
        insertStatisticsRecord(houseId, weight, money, refuseType, DATE_FORMATE_YM, StatisticsTypeEnum.MONTH);
    }

    private void insertStatisticsRecord(long houseId, double weight, BigDecimal money,
                                        String refuseType, String dateFormat, StatisticsTypeEnum typeEnum) {
        String date = DateUtil.formatTimestampToString(System.currentTimeMillis(), dateFormat);
        //判断该户是否已有统计记录
        RecycleStatisticsExample example = new RecycleStatisticsExample();
        example.createCriteria().andHouseholdIdEqualTo(houseId).andRefuseTypeEqualTo(refuseType)
                .andDateEqualTo(date);

        RecycleStatistics statistics = statisticsMapper.selectOneByExample(example);
        if (statistics == null) {
            statistics = new RecycleStatistics();

            statistics.setHouseholdId(houseId);
            statistics.setMoney(money == null ? new BigDecimal(0.0) : money);
            statistics.setWeight(weight);
            statistics.setDate(date);
            statistics.setRefuseType(refuseType);
            statistics.setType(typeEnum.getCode());
            statistics.setCreateTime(System.currentTimeMillis());
            statistics.setUpdateTime(System.currentTimeMillis());
            statisticsMapper.insert(statistics);
        } else {
            statistics.setWeight(new BigDecimal(statistics.getWeight()).add(new BigDecimal(weight)).doubleValue() );
            statistics.setMoney(statistics.getMoney().add(money == null ? new BigDecimal(0.0) : money));

            statistics.setUpdateTime(System.currentTimeMillis());
            statisticsMapper.updateByPrimaryKey(statistics);
        }
    }



    @Override
    public BenefitModel countBenefit(String refuseType, String date, long wechatUserId) throws RecycleRecordException {

//        WechatUserHouseholdExample wechatUserHouseholdExample = new WechatUserHouseholdExample();
//        wechatUserHouseholdExample.createCriteria().andWechatUserIdEqualTo(wechatUserId);
//
//        WechatUserHousehold wechatUserHousehold = wechatUserHouseholdMapper.selectOneByExample(wechatUserHouseholdExample);
//
//        if (wechatUserHousehold == null) {
//            throw new RecycleRecordException(RecycleRecordExceptionEnum.INVALID_HOUSEHOLDCODE_NULL);
//        }
        RecycleStatisticsExample example = new RecycleStatisticsExample();
        example.createCriteria().andHouseholdIdEqualTo(wechatUserId)
                .andRefuseTypeEqualTo(refuseType)
                .andDateEqualTo(date);
        BenefitModel benefitModel = new BenefitModel();
        RecycleStatistics statistics = statisticsMapper.selectOneByExample(example);
        if (statistics == null) {
            benefitModel.setCurrentMonthBenefit(0.0);
            benefitModel.setCurrentMonthWeight(0.0);
            benefitModel.setCurrentDayWeight(0.0);
            benefitModel.setCurrentDayBenefit(0.0);
        } else {
            //判断当前时间与查询date是否在同一月份
            String nowStr = DateUtil.formatTimestampToString(System.currentTimeMillis(), DATE_FORMATE_YM);
            String nowStrtime = DateUtil.formatTimestampToString(System.currentTimeMillis(), DATE_FORMAT_YMD);
           // if (nowStr.equals(date)) {
                //若为当月 则再获取当日的
                RecycleStatisticsExample example2 = new RecycleStatisticsExample();
                example2.createCriteria().andHouseholdIdEqualTo(wechatUserId)
                        .andRefuseTypeEqualTo(refuseType)
                        .andDateEqualTo(nowStrtime);
                RecycleStatistics statistics2 = statisticsMapper.selectOneByExample(example2);
                if(statistics2!=null){
                    benefitModel.setCurrentDayBenefit(statistics2.getMoney().doubleValue());
                    benefitModel.setCurrentDayWeight(statistics2.getWeight());
                }else{
                    benefitModel.setCurrentDayBenefit(0);
                    benefitModel.setCurrentDayWeight(0);
                }

           // }
            benefitModel.setCurrentMonthWeight(statistics.getWeight());
            benefitModel.setCurrentMonthBenefit(statistics.getMoney().doubleValue());
        }
        return benefitModel;

    }

    @Override
    public BenefitStatisticsModel totalBenefit(String wechatUserId) throws RecycleRecordException {

//        WechatUserHouseholdExample wechatUserHouseholdExample = new WechatUserHouseholdExample();
//        wechatUserHouseholdExample.createCriteria().andWechatUserIdEqualTo(Long.valueOf(wechatUserId));
//
//        WechatUserHousehold wechatUserHousehold = wechatUserHouseholdMapper.selectOneByExample(wechatUserHouseholdExample);
//
//        if (wechatUserHousehold == null) {
//            throw new RecycleRecordException(RecycleRecordExceptionEnum.INVALID_HOUSEHOLDCODE_NULL);
//        }
        RecycleStatisticsExample example = new RecycleStatisticsExample();
        example.createCriteria().andHouseholdIdEqualTo(Long.valueOf(wechatUserId))
                .andTypeEqualTo(StatisticsTypeEnum.MONTH.getCode());
        example.setOrderByClause("id desc");
        BenefitStatisticsModel statisticsModel = new BenefitStatisticsModel();
        List<RecycleStatistics> statisticsList = statisticsMapper.selectByExample(example);

        if (statisticsList == null || statisticsList.isEmpty()) {
            statisticsModel.setMoney(0.0);
            statisticsModel.setMonthList(new ArrayList<>());

            return statisticsModel;
        } else {

            BigDecimal totalMoney = new BigDecimal(0.0);
            Map<String, Double> map = new HashMap<>();
            for (RecycleStatistics statistics : statisticsList) {
                if (map.containsKey(statistics.getDate())) {
                    map.put(statistics.getDate(), new BigDecimal(map.get(statistics.getDate()))
                            .add(statistics.getMoney()).doubleValue());
                } else {
                    map.put(statistics.getDate(), statistics.getMoney().doubleValue());
                }
            }
            List<BenefitStatisticsModel.BenefitMonth> monthList = new ArrayList<>();
            for (String key : map.keySet()) {
                BenefitStatisticsModel.BenefitMonth benefitMonth = new BenefitStatisticsModel.BenefitMonth();
                benefitMonth.setDate(key);
                benefitMonth.setMoney(map.get(key));
                totalMoney = totalMoney.add(new BigDecimal(map.get(key)));
                monthList.add(benefitMonth);
            }
            statisticsModel.setMoney(totalMoney.doubleValue());
            statisticsModel.setMonthList(monthList);
        }


        return statisticsModel;
    }
}
